package com.chen.palmar.project.set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.primb.androidlibs.net.entity.HttpResultEntity;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

/**
 * Created by chen on 2018/1/8.
 */

public class EditNameActivity extends BaseActivity {
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tv_top)
    TextView tvTop;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.et_edit_name)
    EditText etEditName;
    private String info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        info = getIntent().getStringExtra("info");

        toolBar.setNavigationOnClickListener(v -> EditNameActivity.this.finish());

        titleBar.setText("修改昵称");

        etEditName.setText(TextUtils.isEmpty(info) ? "" : info);

        tvTop.setText("保存");
        tvTop.setVisibility(View.VISIBLE);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_edit_name;
    }

    @OnClick(R.id.tv_top)
    public void onViewClicked() {
        if (TextUtils.isEmpty(etEditName.getText().toString())) {
            showToast("请输入新昵称后提交");
            return;
        }
        commitNewName(etEditName.getText().toString());
    }

    private void commitNewName(String name) {
        HashMap<String, String> map = new HashMap<>();
        map.put("name", name);
        Subscription subscribe = DataCenter.editUserName(map).subscribe(new HttpSubscriber<HttpResultEntity>(this, showLoading()) {
            @Override
            public void onNext(HttpResultEntity httpResultEntity) {
                if (!TextUtils.isEmpty(httpResultEntity.getMessage())) {
                    showToast(httpResultEntity.getMessage());
                    Intent intent = new Intent();
                    intent.putExtra("info", name);
                    setResult(Activity.RESULT_OK, intent);
                    EditNameActivity.this.finish();
                }
            }
        });
        subscription.add(subscribe);
    }
}
